import { useForm } from "antd/es/form/Form";
import { memo, useCallback, useEffect, useImperativeHandle, useRef } from "react";
import { Button, Drawer, DrawerProps, Form, Input, Spin } from "antd";
import { QueryObserverResult, RefetchOptions, RefetchQueryFilters } from "react-query";
import { IFormRef, ILawsRef, IPage, IRoleRestFillRefHandler } from "../../../types";
import { ILaws, useAddLaws, useUpdateLaws } from "../../../service/laws-service";
import { LawsSelect } from "../../../components/laws-type-select";
import UploadFile from "../../../components/upload-file";


type ILawsFormParams = {
    update?: ILaws;
    open: boolean;
    onRef: React.MutableRefObject<IFormRef | undefined>;
    openFn: (open: boolean) => void;
    refetch: <TPageData>(options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined) => Promise<QueryObserverResult<IPage<ILaws>, unknown>>
} & DrawerProps

const LawsTypeForm = ({ update, onRef, ...props }: ILawsFormParams) => {

    const [form] = useForm();
    const uploadFileRef = useRef<ILawsRef>();
    const lawsSelectRef = useRef<IRoleRestFillRefHandler>();
    const { mutateAsync: addMutation, isLoading: addIsLoading } = useAddLaws();
    const { mutateAsync: updateMutation, isLoading: UIsLoading } = useUpdateLaws();
    useEffect(() => {
        if (update) {
            lawsSelectRef.current?.fill(update.lawsTypeId);
            uploadFileRef.current?.fill(update.lawsUrl)
            form.setFieldsValue({
                lawsTitle: update.lawsTitle,
                lawsId: update.lawsId,
                lawsTypeId: update?.lawsTypeId,
                lawsUnitName: update.lawsUnitName,
            });
        }

    }, [update]);

    /**
   * 更新方法
   */
    const updateHandler = async () => {
        form.setFieldValue("lawsUrl", uploadFileRef.current?.getData());
        const isPass = await form.validateFields();
        if (!isPass) {
            return
        }
        const values = form.getFieldsValue();
        await updateMutation({ ...values, lawsId: update?.lawsId });
        props.refetch();
        props.openFn(false);
        form.resetFields();
    }

    /**
     * 保存方法
     */
    const saveHandler = async () => {
        form.setFieldValue("lawsUrl", uploadFileRef.current?.getData());
        const isPass = await form.validateFields();
        if (!isPass) {
            return
        }
        const values = form.getFieldsValue();
        await addMutation({ ...values });
        props.refetch();
        props.openFn(false);
        form.resetFields();
    }

    /**
     * 向外暴露表单的保存和修改
     */
    useImperativeHandle(onRef, () => ({
        reset: () => {
            form.resetFields();
            uploadFileRef.current?.rest();
            lawsSelectRef.current?.rest();
        },
        save: () => {
            saveHandler();
        },
        update: async () => {
            updateHandler();
        }
    }));

    //设置下拉人员
    const handleChange = useCallback((value: number) => {
        form.setFieldValue("lawsTypeId", value);
    }, []);

    return (
        <Drawer title={'法律法规'} placement="right" width={'35rem'} closable={true} onClose={() => props.openFn(false)} forceRender={true} open={props.open} footer={
            <>
                {
                    update ? (
                        <Button onClick={() => { updateHandler(); }}>
                            修改
                        </Button>
                    ) : (
                        <Button onClick={() => { saveHandler(); }}>
                            保存
                        </Button>
                    )
                }
            </>
        }>
            <Spin spinning={addIsLoading || UIsLoading}>
                <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
                    <Form.Item label={'法律分类'} name={'lawsTypeId'} rules={[{ required: true, message: '法律分类不能为空' }]}>
                        <LawsSelect handleChange={handleChange} onRef={lawsSelectRef} />
                    </Form.Item>
                    <Form.Item label={'法律名称'} name={'lawsTitle'} rules={[{ required: true, message: '法律名称不能为空' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label={'发布单位'} name={'lawsUnitName'} rules={[{ required: true, message: '发布单位不能为空' }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label={'上传文件'} name={'lawsUrl'} rules={[{ required: true, message: '文件不能为空' }]}>
                        <UploadFile onRef={uploadFileRef} />
                    </Form.Item>
                </Form>
            </Spin>
        </Drawer>
    );
};


export default memo(LawsTypeForm)